package com.example.partner.fragment.find;

import static android.content.ContentValues.TAG;
import static android.content.Context.MODE_PRIVATE;
import static com.example.partner.common.ConfigConstant.BASE_URL;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.partner.R;
import com.example.partner.adapter.find.PostAdapter;
import com.example.partner.common.BaseResponse;
import com.example.partner.listener.EndlessScrollListener;
import com.example.partner.model.domain.Post;
import com.example.partner.service.PostService;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RecommendFragment extends Fragment {

    private static final String ARG_POSITION = "position";
    private int current = 1; // 当前页数
    private List<Post> postList = new ArrayList<>(); // 定义列表用于保存所有帖子数据
    private PostAdapter adapter; // 适配器
    private RecyclerView recyclerView;

    private int position;

    public RecommendFragment() {
        // Required empty public constructor
    }

    public static RecommendFragment newInstance(int position) {
        RecommendFragment fragment = new RecommendFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_POSITION, position);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            position = getArguments().getInt(ARG_POSITION);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_find_recommend, container, false);
        // 在这里处理推荐页面的布局和数据显示，可以使用RecyclerView等组件
        recyclerView = rootView.findViewById(R.id.recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
        recyclerView.setLayoutManager(layoutManager);
        // 创建空的适配器并设置给 RecyclerView
        adapter = new PostAdapter(postList, requireContext());
        recyclerView.setAdapter(adapter);
        loadMoreData();
        EndlessScrollListener endlessScrollListener = new EndlessScrollListener(layoutManager, new EndlessScrollListener.LoadMoreListener() {
            @Override
            public void onLoadMore() {
                // 在这里更新 current，并执行加载更多的操作
                current++;
                loadMoreData();
            }
        });
        recyclerView.addOnScrollListener(endlessScrollListener);

        return rootView;
    }
    private void loadMoreData() {
        // 在这里执行加载更多数据的操作，调用 API 或其他方法
        // 在你的 MainActivity 或相关的 Activity 中
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        PostService postService = retrofit.create(PostService.class);
        SharedPreferences sharedPreferences = getContext().getSharedPreferences("CurrentUser", MODE_PRIVATE);
        Long userId = sharedPreferences.getLong("userId", -1);
        Call<BaseResponse<List<Post>>> call = postService.queryHotPost(current,userId);
        call.enqueue(new Callback<BaseResponse<List<Post>>>() {
            @Override
            public void onResponse(Call<BaseResponse<List<Post>>> call, Response<BaseResponse<List<Post>>> response) {
                if (response.isSuccessful()) {
                    List<Post> newPostList = response.body().getData();
                    // 在这里使用 newPostList 更新 UI 或执行其他操作
                    // 添加新数据到已有数据列表
                    if (newPostList!=null){
                        postList.addAll(newPostList);
                        // 通知适配器数据集发生变化
                        if (adapter == null) {
                            // 如果适配器为空，说明是第一次加载数据，需要创建适配器
                            adapter = new PostAdapter(postList, requireContext());
                            recyclerView.setAdapter(adapter);
                        } else {
                            // 如果适配器不为空，说明已经有数据，直接通知适配器数据变化
                            adapter.notifyDataSetChanged();
                        }
                    }

                } else {
                    // 处理错误情况
                    Log.d(TAG, "onResponse:fail");
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<List<Post>>> call, Throwable t) {
                // 网络错误处理
                t.printStackTrace();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("Recommend被销毁");
    }
}
